<!-- 登录页 -->
<template>
  <div class="login-container">

    <el-form
      ref="ruleFormRef" 
      :model="ruleForm" 
      :rules="rules"
      status-icon
      label-width="120px"
      class="demo-ruleForm"
    >
      <h2>商品后台管理系统</h2>
      <!-- 两个输入表单 -->
      <el-form-item prop="username" >
        <el-input :prefix-icon="Avatar" v-model="ruleForm.username" placeholder="请输入用户名" maxlength="11"></el-input>
      </el-form-item>
      <el-form-item prop="pwd">
        <el-input :prefix-icon="Briefcase" v-model="ruleForm.pwd" type="password"  placeholder="请输入密码" maxlength="11"></el-input>
      </el-form-item>
      <!-- 按钮 -->
      <el-form-item>
        <el-button style="width: 100%;"  type="primary" @click="submitForm">登录</el-button>
      </el-form-item>
    </el-form>
  </div>
  
</template>

<script lang='ts' setup>
import { reactive, toRefs, ref} from 'vue'
import { Avatar, Briefcase } from '@element-plus/icons'
import { adminLogin,getUserInfo } from '@/request/api'

// 校验账号方法
const validateUsername = (rule:unknown, value:string, callback:(s?:string)=>void) =>{
  if(value){  //1.先判空
      if(value.length < 3){
        callback('账号长度不能小于3')
      }else{
        callback()
      }
  }else{
    callback('账号不能为空')
  }
}


let state = reactive({
  // 表单数据
  ruleForm: {
    username: '',
    pwd: ''
  },
  // 校验规则
  rules: {
    // 每个属性校验规则是一个数组，也就说明里面可以有多个规则
    username:[
      {
        required: true,
        message: '请输入账号',
        trigger: 'blur',
      },
      { 
        validator: validateUsername,
        trigger: 'blur'
      }
    ],
    pwd:[
      {
        required: true,
        message: '请输入密码',
        trigger: 'blur',
      }
    ]
  }
})

// ruleForm表单属性名称注意不要跟 el-from上的ref值相同
let { ruleForm, rules } = toRefs(state)

// 获取组件实例
let ruleFormRef = ref()
// 点击登录按钮
let submitForm = () =>{
  ruleFormRef.value.validate( async (valid:boolean) => {
    if(valid){  //通过校验
      // 1.发起请求
      let res = await adminLogin({
        password: ruleForm.value.pwd,
        username: ruleForm.value.username
      })

      if(res.code === 200 && res.data){
        // 2.存token
        localStorage.setItem('token', res.data.tokenHead + res.data.token)

        // 3.获取用户信息
        getUserInfo().then(res=>{
          console.log(res)
        })

        // 4.清除校验
      }

    }
  })
}

</script>

<style lang='less' scoped>
  .login-container{
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    
    .demo-ruleForm{
      width: 400px;
      height: 250px;

      h2{
        padding: 10px 0;
        font-size: 24px;
        color: #fff;
        text-align: center;
      }
    }
  }
  

  :deep(.el-form-item__content){
    margin-left: 0 !important;
  }

  :deep(.el-input__inner){
    height: 50px;
    background: transparent;
    border: 1px solid hsla(0,0%,100%,.1);
    background-color: rgba(0,0,0,.1);
    color: #fff;
  }
</style>